package com.yida.gwj.basis.service.impl;

import com.yida.common.core.constant.SecurityConstants;
import com.yida.common.core.exception.ServiceException;
import com.yida.common.core.text.Convert;
import com.yida.common.core.utils.DateUtils;
import com.yida.common.core.utils.StringUtils;
import com.yida.common.security.utils.SecurityUtils;
import com.yida.gwj.api.domain.GwjConfStep;
import com.yida.gwj.api.service.RemoteGwjConfigService;
import com.yida.gwj.basis.domain.GwjInitBusiness;
import com.yida.gwj.basis.domain.GwjInitBusinessCommunity;
import com.yida.gwj.basis.domain.GwjInitBusinessLog;
import com.yida.gwj.basis.domain.request.GwjInitBusinessSaveSubmitRequest;
import com.yida.gwj.basis.enums.GwjInitBusinessCommunityStatus;
import com.yida.gwj.basis.service.IGwjInitBusinessCommunityService;
import com.yida.gwj.basis.service.IGwjInitBusinessLogService;
import com.yida.gwj.basis.service.IGwjInitBusinessService;
import com.yida.gwj.basis.service.IGwjInitSplitBusinessService;
import com.yida.gwj.common.domain.*;
import com.yida.gwj.common.enums.GwjBusinessFlagType;
import com.yida.gwj.common.enums.GwjBusinessStatus;
import com.yida.gwj.common.enums.StepConfigInfoEnum;
import com.yida.gwj.common.service.*;
import com.yida.gwj.common.utils.GwjConvertUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 小区拆分（基础数据管理模块）Service业务层处理
 *
 * @author lqq
 * @date 2022-11-15
 */
@Service
public class GwjInitSplitBusinessServiceImpl implements IGwjInitSplitBusinessService {

	@Resource
	private IGwjInitBusinessLogService logService;

	@Resource
	private IGwjBaseBusinessNumService businessNumService;

	@Resource
	private IGwjInitBusinessService businessService;

	@Resource
	private IGwjInitBusinessCommunityService businessCommunityService;

	@Resource
	private IGwjBaseCommunityService communityService;

	@Resource
	private IGwjBaseBuildService buildService;

	@Resource
	private IGwjBaseHouseService houseService;

	@Resource
	private IGwjBaseOwnerService ownerService;

	@Resource
	private RemoteGwjConfigService remoteGwjConfigService;

	/**
	 * 小区拆分（保存）
	 *
	 * @param saveSubmitRequest 请求参数
	 * @return /
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Long saveBusiness(GwjInitBusinessSaveSubmitRequest saveSubmitRequest) {
		GwjInitBusiness business = saveSubmitRequest.getBusiness();
		GwjInitBusinessCommunity community = saveSubmitRequest.getBusinessCommunity();
		List<GwjInitBusinessCommunity> communities = saveSubmitRequest.getBusinessCommunities();
		//处理业务信息
		//业务流程
		business.setFlowId(remoteGwjConfigService.selectGwjConfBusinessFlagByBizFlagId(business.getBizFlagId(), SecurityConstants.INNER).getData().getFlowId());
		//地区
		business.setAreaId(community.getAreaId());
		//TODO 获取业务编号加锁
		GwjBaseBusinessNum businessNum = businessNumService.getNextNum(business.getAreaId(), business.getBizFlagId());
		//业务编号
		business.setBizNum(Convert.toLong(businessNum.toString()));
		//业务名称
		if (StringUtils.isBlank(business.getBizName())){
			business.setBizName(community.getCommunityName());
		}
		businessService.insert(business);
		//处理业务小区信息
		community.setStatus(GwjInitBusinessCommunityStatus.SPLIT.getCode());
		community.setBizId(business.getBizId());
		//保存小区信息
		businessCommunityService.save(community);
		communities.forEach(c -> {
			if (StringUtils.isBlank(c.getSplitBuild())) {
				throw new ServiceException("拆分小区楼栋不能为空[" + c.getCommunityName() + "]");
			}
			c.setBizId(business.getBizId());
			c.setStatus(GwjInitBusinessCommunityStatus.NORMAL.getCode());
			c.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getRealName());
			c.setCreateTime(DateUtils.getNowDate());
		});
		businessCommunityService.saveBatch(communities);
		//日志
		logService.addSaveLog(business);
		return business.getBizId();
	}

	/**
	 * 小区拆分（保存修改）
	 *
	 * @param saveSubmitRequest 请求参数
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateBusiness(GwjInitBusinessSaveSubmitRequest saveSubmitRequest) {
		GwjInitBusiness business = saveSubmitRequest.getBusiness();
		GwjInitBusinessCommunity community = saveSubmitRequest.getBusinessCommunity();
		List<GwjInitBusinessCommunity> communities = saveSubmitRequest.getBusinessCommunities();
		//检验当前登录账号是否有权限
		businessService.checkPermission(business.getBizId());
		business.setStatus(GwjBusinessStatus.NORMAL.getCode());
		businessService.updateById(business);
		//删除原来的业务小区
		businessCommunityService.deleteByBizId(business.getBizId());
		//保存小区信息
		community.setBizId(business.getBizId());
		community.setStatus(GwjInitBusinessCommunityStatus.SPLIT.getCode());
		businessCommunityService.save(community);
		communities.forEach(c -> {
			c.setBizId(business.getBizId());
			c.setStatus(GwjInitBusinessCommunityStatus.NORMAL.getCode());
		});
		businessCommunityService.saveBatch(communities);
		//日志
		logService.addSaveLog(business);
	}


	/**
	 * 小区拆分（提交）
	 *
	 * @param saveSubmitRequest 请求参数
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void submitBusiness(GwjInitBusinessSaveSubmitRequest saveSubmitRequest) {
		GwjInitBusiness business = saveSubmitRequest.getBusiness();
		GwjInitBusinessLog businessLog = saveSubmitRequest.getBusinessLog();
		if (StringUtils.isNull(business.getBizId())) {
			throw new ServiceException("请先保存业务");
		}
		//检验当前登录账号是否有权限
		businessService.checkPermission(business.getBizId());
		//设置当前步骤日志流程步骤,业务编号
		businessLog.setStepId(business.getStepId());
		businessLog.setBizId(business.getBizId());
		//获取当前步骤所有配置
		List<String> configInfos = remoteGwjConfigService.selectGwjConfStepConfigInfoCodeListByBizFlagId(businessLog.getStepId(), SecurityConstants.INNER).getData();
		//判断是否需要选收件人
		if (StringUtils.containsAny(configInfos, StepConfigInfoEnum.SUBMIT_CHOOSE_USER.getCode()) && StringUtils.isAnyBlank(Convert.toStr(businessLog.getUserId()), businessLog.getRealName())) {
			throw new ServiceException("请选择下一位收件人");
		}
		//当前办理人员
		business.setCurrentOperId(StringUtils.isNull(businessLog.getUserId()) ? SecurityUtils.getUserId() : businessLog.getUserId());
		business.setCurrentOperName(StringUtils.isBlank(businessLog.getRealName()) ? SecurityUtils.getLoginUser().getSysUser().getRealName() : businessLog.getRealName());
		//当前步骤
		GwjConfStep nextStep = remoteGwjConfigService.selectNextGwjConfStepByFlagId(GwjBusinessFlagType.SPLIT.getCode(), business.getStepId(), SecurityConstants.INNER).getData();
		business.setStepId(nextStep.getStepId());
		//更新业务
		business.setStatus(GwjBusinessStatus.NORMAL.getCode());
		businessService.updateById(business);
		//判断当前流程是否可以编辑
		if (StringUtils.containsAny(configInfos, StepConfigInfoEnum.SUBMIT_EDIT.getCode())) {
			GwjInitBusinessCommunity community = saveSubmitRequest.getBusinessCommunity();
			List<GwjInitBusinessCommunity> communities = saveSubmitRequest.getBusinessCommunities();
			if (StringUtils.isNotNull(community) && StringUtils.isNotEmpty(communities)) {
				//删除原来的业务小区
				businessCommunityService.deleteByBizId(business.getBizId());
				//保存业务小区信息
				community.setBizId(business.getBizId());
				community.setStatus(GwjInitBusinessCommunityStatus.SPLIT.getCode());
				businessCommunityService.save(community);
				communities.forEach(c -> {
					c.setBizId(business.getBizId());
					c.setStatus(GwjInitBusinessCommunityStatus.NORMAL.getCode());
				});
				businessCommunityService.saveBatch(communities);
			}
		}
		//日志
		logService.addSubmitLog(business, businessLog);
		//判断是不是已经最后一步
		if (StringUtils.isNull(remoteGwjConfigService.selectNextGwjConfStepByFlagId(GwjBusinessFlagType.SPLIT.getCode(), nextStep.getStepId(), SecurityConstants.INNER).getData())) {
			//将业务数据插入基础数据
			//小区数据
			List<GwjInitBusinessCommunity> businessCommunities = businessCommunityService.getList(business.getBizId(), GwjInitBusinessCommunityStatus.NORMAL.getCode());
			businessCommunities.forEach(c -> {
				//保存基础数据新小区
				GwjBaseCommunity newCommunity = GwjConvertUtil.convert(c, GwjBaseCommunity.class);
				communityService.insertGwjBaseCommunity(newCommunity);
				//修改被拆分的楼栋的小区ID
				if (StringUtils.isNotBlank(c.getSplitBuild())) {
					List<GwjBaseBuild> builds = buildService.selectGwjBaseBuildListByBuildIds(Convert.toLongArray(c.getSplitBuild().trim()));
					if (StringUtils.isNotEmpty(builds)) {
						builds.forEach(b -> {
							b.setCommunityId(newCommunity.getCommunityId());
							b.setAreaId(newCommunity.getAreaId());
							b.setStreetId(newCommunity.getStreetId());
							b.setUpdateBy(SecurityUtils.getLoginUser().getSysUser().getRealName());
							b.setUpdateTime(DateUtils.getNowDate());
						});
						buildService.updateBatchGwjBaseBuild(builds);
						//修改房屋的地区和街道
						String[] buildCodes = builds.stream().map(GwjBaseBuild::getBuildCode).toArray(String[]::new);
						List<GwjBaseHouse> houses = houseService.selectGwjBaseListByBuildCodesAndAreaId(buildCodes, c.getAreaId());
						if (StringUtils.isNotEmpty(houses)) {
							houses.forEach(h -> {
								h.setAreaId(newCommunity.getAreaId());
								h.setStreetId(newCommunity.getStreetId());
								h.setUpdateBy(SecurityUtils.getLoginUser().getSysUser().getRealName());
								h.setUpdateTime(DateUtils.getNowDate());
							});
							houseService.updateBatchGwjBaseHouse(houses);
							//修改业主的地区和街道
							String[] houseCodes = houses.stream().map(GwjBaseHouse::getHouseCode).toArray(String[]::new);
							List<GwjBaseOwner> owners = ownerService.selectGwjBaseListByGwjBaseHouseCodes(houseCodes, c.getAreaId());
							if (StringUtils.isNotEmpty(owners)) {
								owners.forEach(o -> {
									o.setAreaId(newCommunity.getAreaId());
									o.setStreetId(newCommunity.getStreetId());
									o.setUpdateBy(SecurityUtils.getLoginUser().getSysUser().getRealName());
									o.setUpdateTime(DateUtils.getNowDate());
								});
								ownerService.updateBatchGwjBaseOwner(owners);
							}
						}
					}
				}
			});
			//业务更新为完结
			business.setStatus(GwjBusinessStatus.FINISH.getCode());
			businessService.updateById(business);
			//日志
			logService.addFinishLog(business);
		}
	}
}
